/**
 * 示例文件：演示如何使用进阶版axios封装
 */

import { http, HttpRequest, cancelRequest } from '@/utils/http';
import { RequestConfig } from '@/utils/http/types';
import { UserService, TableService } from './service';

// 示例1：直接使用默认实例发起请求
export async function example1() {
  try {
    // GET 请求
    const response1 = await http.get('/api/users');
    console.log('GET 请求结果:', response1);

    // POST 请求
    const response2 = await http.post('/api/users', { name: '张三', age: 30 });
    console.log('POST 请求结果:', response2);

    // 带参数的 GET 请求
    const response3 = await http.get('/api/users', { page: 1, limit: 10 });
    console.log('带参数的 GET 请求结果:', response3);

    // 自定义配置的请求
    const response4 = await http.post('/api/users', { name: '李四', age: 25 }, {
      showLoading: true,
      loadingText: '提交中...',
      retry: true,
      retryCount: 3
    });
    console.log('自定义配置的请求结果:', response4);
  } catch (error) {
    console.error('请求错误:', error);
  }
}

// 示例2：使用 Service 层发起请求
export async function example2() {
  try {
    // 获取用户信息
    const userInfo = await UserService.getUserInfo();
    console.log('用户信息:', userInfo);

    // 登录
    const loginResult = await UserService.login({
      username: 'admin',
      password: '123456'
    });
    console.log('登录结果:', loginResult);

    // 获取表格数据（带 loading）
    const tableData = await TableService.getTableData({ page: 1, limit: 20 });
    console.log('表格数据:', tableData);
  } catch (error) {
    console.error('Service 请求错误:', error);
  }
}

// 示例3：创建自定义实例
export function createCustomInstance() {
  // 创建自定义配置
  const customConfig: RequestConfig = {
    baseURL: 'https://custom-api.example.com',
    timeout: 10000,
    headers: {
      'X-Custom-Header': 'CustomValue'
    },
    // 自定义拦截器
    interceptors: {
      requestInterceptor: (config) => {
        console.log('自定义请求拦截器');
        return config;
      },
      responseInterceptor: (response) => {
        console.log('自定义响应拦截器');
        return response;
      }
    }
  };

  // 创建自定义实例
  const customHttp = new HttpRequest(customConfig);

  return customHttp;
}

// 示例4：请求取消
export function example4() {
  const cancelTokenKey = 'user-list';

  // 发起可取消的请求
  const fetchUserList = async () => {
    try {
      const result = await http.get('/api/users', { page: 1 }, {
        cancelToken: cancelTokenKey
      });
      console.log('用户列表:', result);
    } catch (error) {
      console.error('获取用户列表错误:', error);
    }
  };

  // 取消请求
  const cancelUserListRequest = () => {
    cancelRequest(cancelTokenKey);
    console.log('已取消用户列表请求');
  };

  return {
    fetchUserList,
    cancelUserListRequest
  };
}

// 示例5：上传文件
export async function uploadFileExample(file: File) {
  try {
    const result = await http.upload('/api/upload', file, 'file', {
      type: 'avatar',
      userId: '123'
    });
    console.log('文件上传结果:', result);
    return result;
  } catch (error) {
    console.error('文件上传错误:', error);
    throw error;
  }
}

// 示例6：下载文件
export async function downloadFileExample(fileId: string, fileName: string) {
  try {
    const blob = await http.download(`/api/files/${fileId}`);
    
    // 创建下载链接
    const url = window.URL.createObjectURL(blob);
    const link = document.createElement('a');
    link.href = url;
    link.setAttribute('download', fileName);
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
    window.URL.revokeObjectURL(url);
    
    return true;
  } catch (error) {
    console.error('文件下载错误:', error);
    throw error;
  }
}

// 示例7：并发请求
export async function concurrentRequestsExample() {
  try {
    const [users, roles, permissions] = await Promise.all([
      http.get('/api/users'),
      http.get('/api/roles'),
      http.get('/api/permissions')
    ]);
    
    console.log('用户列表:', users);
    console.log('角色列表:', roles);
    console.log('权限列表:', permissions);
    
    return { users, roles, permissions };
  } catch (error) {
    console.error('并发请求错误:', error);
    throw error;
  }
} 